package com.cxria.springboottest.service.impl;

import com.cxria.springboottest.entity.User;
import com.cxria.springboottest.repository.RoleRepository;
import com.cxria.springboottest.repository.UserRepository
import com.cxria.springboottest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional;

@Service
class UserServiceImpl implements UserService, UserDetailsService {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private RoleRepository roleRepository;

	User getUser(String name){
		return userRepository.findByName(name);
	}

	User getByUsername(String username) {
		return userRepository.findByUsername(username);
	}

	User getById(long userId) {
		return userRepository.findOne(userId);
	}

	@Transactional
	void delete(long id) {
		userRepository.delete(id);
	}

	@Override
	UserDetails loadUserByUsername(String s) {
		def user = userRepository.findByUsername(s)
		if(!user){
			throw UsernameNotFoundException
		}
		return user
	}

}
